import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Input, Button, message} from 'antd';
import {
  systemPlatNewsSendVerificationCode,
  systemPlatNewsVerificationCode,
  systemPerAccountInfoUpdatePassword
} from "../../../services/api";
import bcx_utils from "../../../common/bcx_utils";
// @connect(state => ({
//   monitor: state.monitor,
// }))

const FormItem = Form.Item;
@Form.create()

/**
 * 修改密码
 */
export default class InitialPasswordModification extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 60,//短信发送时间限制
      ifSendCode: false,//是否已经发送验证码
      companyInfo: this.props.companyInfo,
      confirmDirty: false,//是否第一次检验
    }
    ;
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.setState({companyInfo: this.props.companyInfo});
  }

  componentWillUnmount = () => {
    if (this.codeTime) {
      clearInterval(this.codeTime);
    }
  }

  componentWillReceiveProps = (nextProps, newState) => {
    console.log("InitialPasswordModification", nextProps);
    console.log("InitialPasswordModification", this.props);
    this.setState({companyInfo: nextProps.companyInfo});
  }
  /******************************ajax请求******************************/
    //获取手机验证码
  systemPlatNewsSendVerificationCode = () => {
    const mobile = this.props.form.getFieldValue("mobile");
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      systemPlatNewsSendVerificationCode({t: "", sign: "", mobile}).then(
        (data) => {
          console.log(data);
          resolve(false);
        },
        (err) => {
          console.log(err);
          resolve(false);
        }
      );
    }));
  }
  // 初始化密码修改
  systemPerAccountInfoUpdatePassword = (ajaxPara) => {
    //验证码通过再 修改密码
    systemPerAccountInfoUpdatePassword(ajaxPara).then(
      (data) => {
        console.log(data);
        message.success(data.msg);
        this.props.nextStep();
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //记录是否修改过密码
  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({confirmDirty: this.state.confirmDirty || !!value});
  }
  //确认管理密码   验证2次输入的密码
  compareToFirstPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码输入不一致!');
    } else {
      callback();
    }
  }
  //新管理密码     验证2次输入的密码
  validateToNextPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], {force: true});
    }
    callback();
  }


  /******************************相关事件******************************/
    //表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, {mobile, password, code}) => {
      if (!err) {
        // console.log('Received values of form: ', values);
        //判断验证码
        bcx_utils.preventRepeatAsync(callback => callback((resolve) => {
          systemPlatNewsVerificationCode({mobile, code})
            .then(
              (data) => {
                resolve(false);
                return systemPerAccountInfoUpdatePassword({mobile, password});
              },
              (err) => {
                resolve(false);
                return false;
              }
            )
            .then(data => {
              if (!data) {
                return;
              }
              console.log(data);
              this.props.nextStep();
            }, err => {
              console.log(err);
            });
        }));
      }
    });
  }

  //发送验证码
  sendCode = () => {
    const {ifSendCode} = this.state;
    const mobile = this.props.form.getFieldValue("mobile");
    const mobileError = this.props.form.getFieldError("mobile");
    //判断是否正确的手机号码，然后开始计时
    if (mobile !== undefined && mobileError === undefined) {
      if (ifSendCode) {
        return;
      } else {
        this.setState({ifSendCode: true});
        this.systemPlatNewsSendVerificationCode();
        this.codeTime = window.setInterval(() => {
          const {count} = this.state;
          if (count !== 1) {
            this.setState(preState => ({
              count: preState.count - 1,
            }));
          } else {
            clearInterval(this.codeTime);
            this.setState({ifSendCode: false, count: 60});
          }
        }, 1000);
      }
    } else {
      bcx_utils.preventRepeat(() => {
        message.error("请输入正确的手机号码", 1.8);
      }, 2000);
    }
  }


  /******************************render******************************/
    //验证码
  renderValidButton = () => {
    const {ifSendCode, count} = this.state;
    return (
      <Button type="primary" disabled={ifSendCode} className="getCaptcha" onClick={this.sendCode}
      >
        {ifSendCode ? `${count} s` : '验证码'}
      </Button>
    );
  }


  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: {span: 6},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 12},
        sm: {span: 12},
      },
    };
    const {comName = "", legalRepPhone = ""} = this.state.companyInfo;
    return (
      <Container>
        <header className="password-header">初始密码修改</header>
        <Form onSubmit={this.handleSubmit} style={{marginTop: 24}}
        >
          <FormItem {...formItemLayout} label="当前企业"
          >
            <span>{comName}</span>
          </FormItem>
          <FormItem {...formItemLayout} label="绑定手机号码"
          >
            {getFieldDecorator('mobile', {
              initialValue: legalRepPhone,
              rules: [{
                pattern: /^1[0-9]{10}$/, message: '请输入正确手机号码!',
              }, {required: true, message: '请输入您的手机号码'}],
            })(
              <Input placeholder="请输入您的手机号码" disabled/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="验证码">
            <div style={{display: 'flex'}}>
              <div style={{flex: 1}}>
                {getFieldDecorator('code', {
                  rules: [{
                    required: true, message: '请输入验证码！',
                  }],
                })(
                  <Input placeholder="请输入"/>
                )}
              </div>
              {this.renderValidButton()}
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label="新管理密码"
          >
            {getFieldDecorator('password', {
              rules: [{
                required: true, message: '请输入密码！',
              }, {validator: this.validateToNextPassword}],
            })(
              <Input placeholder="请输入" maxLength="10"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="确认管理密码">
            {getFieldDecorator('confirm', {
              rules: [
                {required: true, message: '请再次输入密码'},
                {validator: this.compareToFirstPassword,}
              ],
            })(
              <Input placeholder="请再次输入密码" type="password" onBlur={this.handleConfirmBlur}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label=" " colon={false}
          >
            {/*<Button style={{marginRight: "8px"}}>取消</Button>*/}
            <Button className="submit" type="primary" htmlType="submit">保存</Button>
          </FormItem>
        </Form>
      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .getCaptcha{
        top:4px;
        margin-left:8px;
         &:disabled{
          background:rgb(204, 204, 204);
          color:#fff;
        }
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
}`;
